#include <vector>
#include <queue>

using std::queue;
using std::vector;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    vector<double> averageOfLevels(TreeNode* root) {
        queue<TreeNode*> q;
        vector<double> v;
        q.push(root);
        int count = 1;
        double sum = 0;
        int sum_num = 0;
        TreeNode* tmp = nullptr;
        while (!q.empty()) {
            tmp = q.front();
            q.pop();
            count--;
            sum += tmp->val;
            sum_num++;
            if (count == 0) {
                v.push_back(sum / sum_num);
                sum = 0;
                sum_num = 0;
            }
            if (tmp->left != nullptr) {
                q.push(tmp->left);
            }
            if (tmp->right != nullptr) {
                q.push(tmp->right);
            }
            if (count == 0) {
                count = q.size();
            }
        }
        return v;
    }
};